package com.midian.action.mc.push;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.json.JSONException;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.midian.action.mc.common.AjaxAction;
import com.midian.common.annotation.FunctionAnnotationOverride;
import com.midian.common.baiduPush.AndroidPush;
import com.midian.common.iosPush.IosPush;
import com.midian.common.system.SysStatic;
import com.midian.common.utils.DateHelper;
import com.midian.model.device.Device;
import com.midian.model.push.PushMsg;
import com.midian.model.user.User;
import com.midian.model.user.vo.UserInfoVo;
import com.midian.service.device.IDeviceService;
import com.midian.service.push.IPushMsgService;
import com.opensymphony.xwork2.ActionContext;

import net.sf.json.JSONObject;

/**
 * 推送消息Action
 * @author Mengfh
 *
 */
@Scope("prototype")
@Controller("pushMsgAction")
@FunctionAnnotationOverride(isAction = true, auth = "推送消息管理")
public class PushMsgAction extends AjaxAction<PushMsg> {
	/**推送消息实体*/
	private PushMsg entity;
	/**推送消息实体列表*/
	private List<PushMsg> rows;
	/**推送消息业务*/
	private IPushMsgService pushMsgService;
	/**设备业务*/
	private IDeviceService deviceService;
	
	public PushMsg getEntity() {
		return entity;
	}
	public void setEntity(PushMsg entity) {
		this.entity = entity;
	}
	@Resource(name = "deviceService")
	public void setDeviceService(IDeviceService deviceService) {
		this.deviceService = deviceService;
	}
	@Resource(name = "pushMsgService")
	public void setPushMsgService(IPushMsgService pushMsgService) {
		this.service = pushMsgService;
		this.pushMsgService = pushMsgService;
	}
	@Override
	protected PushMsg dytEntity() {
		if(this.entity == null) {
			this.entity = new PushMsg();
		}
		return getEntity();
	}
	@Override
	protected void dyEntity(PushMsg t) {
		setEntity(t);
	}
	@Override
	public void setRows(List<PushMsg> rows) {
		this.rows = rows;
	}
	@Override
	public List<PushMsg> getRows() {
		return rows;
	}
	
	@Override
	public String saveInfo(){
			try {
				Map<String, Object> session = ActionContext.getContext().getSession();
				UserInfoVo userInfoVo = (UserInfoVo) session.get(SysStatic.MC_LOGIN);
				JSONObject pushJson = new JSONObject();
				//保存推送消息
				PushMsg pushMsg = new PushMsg();
				User user = new User();
				user.setId(userInfoVo.getId());
				pushMsg.setTitle(this.entity.getTitle());//新闻标题
				pushMsg.setContent(this.entity.getContent());//新闻内容
				pushMsg.setCreateTime(new Date());//创建时间
				pushMsg.setDelFlag(SysStatic.NORMALDELFLAG);//状态正常
				PushMsg pm = pushMsgService.add(pushMsg);//保存
				
				//安卓推送
				pushJson.put("title", this.entity.getTitle());
				pushJson.put("description", this.entity.getContent());
				//安卓推送
				List<Device> deviceList = this.deviceService.getDeviceListByIsReceive(IDeviceService.ISRECEIVE_YES,IDeviceService.DEVICE_ANDRIOD);//选择出isreceive为1的安卓用户
				for (int i = 0; i < deviceList.size(); i++) {
					if (deviceList.get(i).getDeviceToken()!=null) {
						AndroidPush.pushToSingleDevice(entity.getTitle(), entity.getContent(), deviceList.get(i).getDeviceToken());
					}
				}
				LOG.debug("===========【PushMsgAction】安卓推送完成===============");
//				AndroidPush.pushToAll(pushJson.toString());	
				
				//ios推送json
				final String title =dytEntity().getTitle();
				String timestamp=String.valueOf(System.currentTimeMillis());
				String type = "0";
				final Map<String,String> sendMap = new HashMap<String,String>();
				JSONObject iosPushJson = new JSONObject();
				iosPushJson.put("d", DateHelper.getDateStr("yyyy-MM-dd HH:mm:ss", new Date()));//添加时间
				iosPushJson.put("ts", timestamp);//时间戳
				type = SysStatic.PUSH_TYPE_BROADCAST; //0：广播
				iosPushJson.put("t",type); //类型			
				iosPushJson.put("k", dytEntity().getTitle()); //标题
				iosPushJson.put("v", dytEntity().getContent()); //内容
				iosPushJson.put("u", userInfoVo.getId());//用户id
				iosPushJson.put("p", pm.getId());//推送id
				sendMap.put("d",iosPushJson.toString());
//				//ios推送
				final IosPush push = new IosPush();
				LOG.debug("===========【PushMsgAction】消息拼接完成，开始启用线程处理ios推送===============");
				new Thread(new Runnable() {	
					@Override
					public void run() {
						Integer totalPages = opIosNewsPush(push, title, sendMap,1, 20, 1); //查询第1页，以便获取总页数，所以第一次查询时，指定总页数为1
						opIosNewsPush(push, title,sendMap, 2, 20, totalPages); //根据返回的总页数，从第2页开始循环推送
					}
				}).start();
				LOG.debug("===========【PushMsgAction】ios推送线程启用已完成===============");
			} catch (Exception e) {
				LOG.error(e.getMessage());
			}
		return SAVEINFO;
	}
	
		/**
		 * 处理IOS资讯推送
		 * @param push IOS推送对象
		 * @param pushJson 推送JSON字符串
		 * @param currentPage 页码
		 * @param pageSize 每页行数
		 * @param totalPages 总页数
		 * @return
		 */
		private Integer opIosNewsPush(IosPush push, String title,Map<String,String> sendMap, int currentPage, int pageSize, int totalPages) {
			for (int i = currentPage; i <= totalPages; i++) {
				List<Device> iosDeviceList = deviceService.getDeviceListByType(IDeviceService.DEVICE_IOS, currentPage, pageSize);
				if(!iosDeviceList.isEmpty()){
					totalPages = iosDeviceList.get(0).getPager().getTotalPages();
				}
				for(Device device :iosDeviceList){							
					try {
						LOG.debug("设备号"+device.getDeviceToken());
						push.add(device.getDeviceToken(),title, 1,null,sendMap);
					} catch (JSONException e) {
						LOG.error(e.getMessage());
					}
				}
			}
			return totalPages;
		}
	

}
